import { defineStore } from 'pinia';
import api from "@/api/index.js";
import { getQueryParam } from "@/utils/utils.js";

export const useUserStore = defineStore('user', {
	state: () => {
		return {
			userInfo: uni.getStorageSync('userInfo') || {},
			token: uni.getStorageSync('token'),
			isRoleBusiness: uni.getStorageSync('isRoleBusiness'),
			registerInviteCode: uni.getStorageSync('registerInviteCode') || '', // 注删邀请码（新用户登录时用）
			isShowLoginPanel: false, // 是否显示登录面板(c-customer-tabbar.vue已添加一级页面共用的登录)
		}
	},

	getters: {

	},

	actions: {
		// 重置store
		RESET_STORE() {
			this.$reset();
		},

		// 处理景场参数
		SET_PATH_SCENE(scene) {
			if (!scene) {
				this.SET_REGISTER_INVITE_CODE('');
				return;
			}
			scene = decodeURIComponent(scene);
			const code = getQueryParam(scene, 'code');
			this.SET_REGISTER_INVITE_CODE(code || '');
		},

		// 设置注册邀请码
		SET_REGISTER_INVITE_CODE(code) {
			this.registerInviteCode = code;
			uni.setStorageSync('registerInviteCode', code);
		},

		// 显示登录面板
		SET_SHOW_LOGIN_PANEL() {
			if (this.token) return;
			this.isShowLoginPanel = true;
		},

		// 隐藏登录面板
		SET_HIDE_LOGIN_PANEL() {
			this.isShowLoginPanel = false;
		},

		// 设置token
		SET_TOKEN(token) {
			uni.setStorageSync('token', token);
			this.token = token;
			this.SET_HIDE_LOGIN_PANEL();
		},

		// 清空token
		CLEAR_TOKEN() {
			uni.clearStorageSync();
			this.token = null;
		},

		// 设置用户信息
		SET_USERINFO(data) {
			uni.setStorage({
				key: 'userInfo',
				data: data
			});
			this.userInfo = data;
		},

		// 获取用户信息
		async getUserInfo() {
			const res = await api.user_api.getUserProfile();
			this.SET_USERINFO(res.data.data);
		},

		// 切换角色
		SET_TOGGLE_ROLE() {
			this.isRoleBusiness = !this.isRoleBusiness;
			uni.setStorageSync('isRoleBusiness', this.isRoleBusiness);
			uni.reLaunch({
				url: '/pages/index/index'
			});
		},
	},
})